import React, { useEffect, useState } from 'react';
import {
  Modal,
  Form,
  Input,
  Select,
  Descriptions,
  Timeline,
  Spin,
  message,
  Row,
  Col,
  Button,
  Popover,
} from 'antd';
import { FormInstance } from 'antd/es/form';
import { AbilityItem, OrganizationItem } from 'admin/schema/Cas';
import { getAbilityAuditLogs, getAuditUserByType } from 'admin/servers/modules/Cas';
import { filter, find, findIndex, get, isNumber, map, some, startsWith } from 'lodash';
import { downLoadByUrl } from '../utils';
import { CheckCircleOutlined, ClockCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { getTimelineItemProps } from './TemplateAuditModal';

interface Props {
  visible: boolean;
  title: string;
  organizations: Omit<OrganizationItem, 'children' | 'description'>[];
  onOk: () => void;
  onCancel: () => void;
  form: FormInstance;
  ability: AbilityItem | null;
  userInfo: any;
}

interface AuditLog {
  id: string;
  operationAt: number;
  operator: string;
  status: string;
  remark: string;
  abilityApplicationId: string;
  createdAt: number;
  taskName: string;
  userInfo: {
    id: string;
    username: string;
    nickname: string;
    phone: string;
    email: string;
    status: number;
    face: string;
    createdTime: number;
  };
}

interface AuditUser {
  stepName: string;
  auditUserList: {
    userId: string;
    userName: string;
    nickName: string;
  }[];
}

const AbilityAuditModal: React.FC<Props> = ({
  visible,
  title,
  organizations,
  onOk,
  onCancel,
  form,
  ability,
  userInfo,
}) => {
  const [loading, setLoading] = useState(false);
  const [auditLogs, setAuditLogs] = useState<AuditLog[]>([]);
  const [auditUsers, setAuditUsers] = useState<AuditUser[]>([]);
  const hasAuditPermission =
    (some(userInfo?.permissions, permission =>
      startsWith(permission?.code, 'CAPABILITY_AUDIT_CAPABILITY_AUDIT_LEVEL1')
    ) &&
      ability?.status === 'PENDING') ||
    (some(userInfo?.permissions, permission =>
      startsWith(permission?.code, 'CAPABILITY_AUDIT_CAPABILITY_AUDIT_LEVEL2')
    ) &&
      ability?.status === 'UNDER_REVIEW');

  // 获取审核日志
  const fetchAuditLogs = async () => {
    if (!ability?.id) return;
    setLoading(true);
    try {
      const response = await getAbilityAuditLogs(ability.id);
      if (response.status === 200) {
        setAuditLogs(response.data);
      }
    } catch (error) {
      console.error('获取审核日志出错:', error);
      message.error('获取审核日志失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchAuditUsers = async () => {
    try {
      const response = await getAuditUserByType('ABILITY');
      if (response.status === 200) {
        setAuditUsers([
          { stepName: '提交', auditUserList: [] },
          ...response.data.stepAuditUsers,
          { stepName: '结束', auditUserList: [] },
        ]);
      }
    } catch (error) {
      console.error('获取审批流程出错:', error);
      message.error('获取审批流程失败');
    }
  };

  useEffect(() => {
    if (visible && ability) {
      fetchAuditLogs();
      fetchAuditUsers();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible, ability]);

  const renderFileDownload = (fileUrl: string | undefined) => {
    if (!fileUrl) return '-';
    const urls = JSON.parse(fileUrl);
    if (!Array.isArray(urls) || urls.length === 0) return '-';
    return map(urls, (url: any, index: number) => (
      <a key={index} onClick={() => downLoadByUrl(url.path, url.realName)}>
        {url.realName}
      </a>
    ));
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'PENDING':
        return '待审核';
      case 'UNDER_REVIEW':
        return '审核中';
      case 'APPROVED':
        return '审核通过';
      case 'REJECTED':
        return '审核驳回';
      default:
        return status;
    }
  };

  return (
    <Modal
      title={title}
      visible={visible}
      onOk={onOk}
      onCancel={onCancel}
      width={1000}
      maskClosable={false}
      okButtonProps={{
        style: {
          display: hasAuditPermission ? 'inline' : 'none',
        },
      }}
    >
      <Spin spinning={loading}>
        <Row gutter={24}>
          {/* 申请信息 */}
          <Col span={14}>
            <div style={{ marginBottom: 24 }}>
              <h3>申请信息</h3>
              <Descriptions column={2}>
                <Descriptions.Item label="单位">
                  {find(organizations, { id: ability?.org })?.name}
                </Descriptions.Item>
                <Descriptions.Item label="年份">{ability?.year}</Descriptions.Item>
                <Descriptions.Item label="类型">{ability?.type}</Descriptions.Item>
                <Descriptions.Item label="数量">
                  {ability?.quantity
                    ? `${ability?.quantity}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
                    : '-'}
                  {ability?.unit}
                </Descriptions.Item>
                <Descriptions.Item label="阈值">
                  {isNumber(ability?.threshold) ? `${ability.threshold * 100}%` : '-'}
                </Descriptions.Item>
                <Descriptions.Item label="状态">
                  {getStatusText(ability?.status || '')}
                </Descriptions.Item>
                <Descriptions.Item label="申请时间">
                  {ability?.applyTime ? new Date(ability.applyTime).toLocaleString() : ''}
                </Descriptions.Item>
                <Descriptions.Item contentStyle={{ flexDirection: 'column' }} label="证明材料">
                  {renderFileDownload(ability?.materials)}
                </Descriptions.Item>
              </Descriptions>
            </div>
          </Col>

          {/* 审核日志 */}
          <Col span={10}>
            <div style={{ marginBottom: 24, borderLeft: '1px solid #f0f0f0', paddingLeft: 24 }}>
              <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16 }}>
                <h3 style={{ margin: 0, marginRight: 8 }}>审核日志</h3>
                <Popover
                  title="审批流程"
                  content={
                    <Timeline mode="alternate" style={{ width: 300 }}>
                      {map(auditUsers, (step, index) => {
                        const currentStatus = get(auditLogs, '[0].status');
                        const currentStepIndex = findIndex(auditUsers, {
                          stepName: auditLogs[0]?.taskName,
                        });
                        const content = (
                          <div>
                            <div style={{ fontWeight: 'bold' }}>{step.stepName}</div>
                            <div style={{ fontSize: '12px', color: '#666' }}>
                              {map(
                                filter(step.auditUserList, item => item.userName !== 'admin'),
                                user => (
                                  <span key={user.userId} style={{ marginRight: 8 }}>
                                    {user.nickName || user.userName}
                                  </span>
                                )
                              )}
                            </div>
                          </div>
                        );
                        if (currentStatus === 'REJECTED') {
                          if (index < currentStepIndex) {
                            return (
                              <Timeline.Item
                                key={index}
                                dot={<CheckCircleOutlined className="timeline-clock-icon" />}
                                color="green"
                              >
                                {content}
                              </Timeline.Item>
                            );
                          }
                          if (index === currentStepIndex) {
                            return (
                              <Timeline.Item
                                key={index}
                                dot={<CloseCircleOutlined className="timeline-clock-icon" />}
                                color="red"
                              >
                                {content}
                              </Timeline.Item>
                            );
                          }
                        }
                        return (
                          <Timeline.Item
                            {...getTimelineItemProps(index, currentStatus, currentStepIndex)}
                          >
                            {content}
                          </Timeline.Item>
                        );
                      })}
                    </Timeline>
                  }
                  trigger="hover"
                >
                  <Button type="link" style={{ padding: 0, height: 'auto' }}>
                    审批流程
                  </Button>
                </Popover>
              </div>
              <Timeline>
                {map(auditLogs, log => (
                  <Timeline.Item key={log.id}>
                    <p>
                      {log?.userInfo?.nickname || log?.userInfo?.username || log.operator} 于{' '}
                      {new Date(log.operationAt).toLocaleString()} 完成 {log.taskName}
                    </p>
                    {log.remark && <p>备注：{log.remark}</p>}
                  </Timeline.Item>
                )).reverse()}
                {['PENDING', 'UNDER_REVIEW'].includes(get(auditLogs, '[0].status')) && (
                  <Timeline.Item
                    dot={<ClockCircleOutlined className="timeline-clock-icon" />}
                    color="red"
                  >
                    {get(auditLogs, '[0].status') === 'PENDING' && (
                      <>
                        等待 {get(auditUsers, '[1].stepName')} （审批人：
                        {map(
                          filter(
                            get(auditUsers, '[1].auditUserList'),
                            item => item.userName !== 'admin'
                          ),
                          item => item.nickName || item.userName
                        ).join(', ')}
                        ）
                      </>
                    )}
                    {get(auditLogs, '[0].status') === 'UNDER_REVIEW' && (
                      <>
                        等待{' '}
                        {get(auditUsers, [
                          findIndex(auditUsers, { stepName: auditLogs[0]?.taskName }) + 1,
                          'stepName',
                        ])}{' '}
                        （审批人：
                        {map(
                          filter(
                            get(auditUsers, [
                              findIndex(auditUsers, { stepName: auditLogs[0]?.taskName }) + 1,
                              'auditUserList',
                            ]),
                            item => item.userName !== 'admin'
                          ),
                          item => item.nickName || item.userName
                        ).join(', ')}
                        ）
                      </>
                    )}
                  </Timeline.Item>
                )}
                {get(auditLogs, '[0].status') === 'REJECTED' && (
                  <Timeline.Item
                    dot={<CloseCircleOutlined className="timeline-clock-icon" />}
                    color="red"
                  >
                    审核驳回
                  </Timeline.Item>
                )}
                {get(auditLogs, '[0].status') === 'APPROVED' && (
                  <Timeline.Item
                    dot={<CheckCircleOutlined className="timeline-clock-icon" />}
                    color="green"
                  >
                    审核通过
                  </Timeline.Item>
                )}
              </Timeline>
            </div>
          </Col>
        </Row>

        {/* 审核表单 - 只在有审核权限且状态不为已通过时显示 */}
        {hasAuditPermission && (
          <div>
            <h3>审核表单</h3>
            <Form form={form} layout="vertical">
              <Form.Item
                name="auditStatus"
                label="审核结果"
                rules={[{ required: true, message: '请选择审核结果' }]}
              >
                <Select>
                  <Select.Option value="APPROVED">通过</Select.Option>
                  <Select.Option value="REJECTED">驳回</Select.Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="remark"
                label="审核备注"
                rules={[
                  { required: true, message: '请输入审核备注' },
                  { max: 255, message: '请输入255位以内字符' },
                ]}
              >
                <Input.TextArea rows={4} placeholder="请输入审核备注" />
              </Form.Item>
            </Form>
          </div>
        )}
      </Spin>
    </Modal>
  );
};

export default AbilityAuditModal;
